const { Sequelize } = require('sequelize');

// 数据库配置
const sequelize = new Sequelize('lingxi_system', 'root', '888mei525', {
  host: 'localhost',
  dialect: 'mysql',
  timezone: '+08:00',
  logging: false
});

async function seedData() {
  try {
    // 测试数据库连接
    await sequelize.authenticate();
    console.log('数据库连接成功');
    
    // 先检查是否已有客户数据
    const [customerCount] = await sequelize.query('SELECT COUNT(*) as count FROM customers');
    console.log(`客户表当前记录数: ${customerCount[0].count}`);
    
    // 如果没有客户数据，则创建一些示例客户
    if (customerCount[0].count === 0) {
      console.log('正在创建示例客户数据...');
      
      const customers = [];
      for (let i = 1; i <= 10; i++) {
        customers.push({
          name: `客户${String.fromCharCode(65 + i - 1)}`,
          code: `C${1000 + i - 1}`,
          contact_persons: JSON.stringify([{
            name: `联系人${i}`,
            department: '采购部',
            position: '采购经理',
            phone: `1380013${String(8000 + i).padStart(4, '0')}`,
            email: `contact${i}@customer.com`,
            remark: ''
          }]),
          status: 1,
          created_at: new Date(),
          updated_at: new Date()
        });
      }
      
      const customerQuery = `
        INSERT INTO customers (name, code, contact_persons, status, created_at, updated_at) VALUES ?
      `;
      
      const customerValues = customers.map(customer => [
        customer.name, customer.code, customer.contact_persons, customer.status, customer.created_at, customer.updated_at
      ]);
      
      await sequelize.query(customerQuery, {
        replacements: [customerValues],
        type: Sequelize.QueryTypes.INSERT
      });
      
      console.log(`成功插入 ${customers.length} 条客户数据`);
    }
    
    // 检查是否已有销售订单数据
    const [orderCount] = await sequelize.query('SELECT COUNT(*) as count FROM sales_orders');
    console.log(`销售订单表当前记录数: ${orderCount[0].count}`);
    
    // 如果没有销售订单数据，则创建一些示例订单
    if (orderCount[0].count === 0) {
      console.log('正在创建示例销售订单数据...');
      
      const orders = [];
      const orderStatuses = ['pending', 'paid', 'shipped', 'completed', 'cancelled'];
      const invoiceStatuses = ['uninvoiced', 'invoiced', 'sent'];
      const collectionStatuses = ['pending', 'contacted', 'promised', 'paid', 'difficult'];
      
      for (let i = 1; i <= 20; i++) {
        const order = {
          platform_order_id: `ZCY20231108${String(i).padStart(4, '0')}`,
          customer_id: Math.floor(Math.random() * 10) + 1, // 使用已创建的客户ID
          order_amount: Math.floor(Math.random() * 100000) + 1000,
          order_status: orderStatuses[Math.floor(Math.random() * orderStatuses.length)],
          order_date: new Date(Date.now() - Math.floor(Math.random() * 30) * 24 * 60 * 60 * 1000),
          platform_source: Math.random() > 0.5 ? 'zcy' : 'manual',
          invoice_status: invoiceStatuses[Math.floor(Math.random() * invoiceStatuses.length)],
          invoice_date: new Date(Date.now() - Math.floor(Math.random() * 20) * 24 * 60 * 60 * 1000),
          responsible_salesman: `销售${String.fromCharCode(65 + (i % 5))}`,
          invoice_number: `INV20231108${String(i).padStart(4, '0')}`,
          collection_status: collectionStatuses[Math.floor(Math.random() * collectionStatuses.length)],
          collection_count: Math.floor(Math.random() * 5),
          last_collection_date: new Date(Date.now() - Math.floor(Math.random() * 10) * 24 * 60 * 60 * 1000),
          last_collection_result: `催款结果${i}`,
          next_followup_date: new Date(Date.now() + Math.floor(Math.random() * 10) * 24 * 60 * 60 * 1000),
          created_at: new Date(),
          updated_at: new Date()
        };
        
        orders.push(order);
      }
      
      const orderQuery = `
        INSERT INTO sales_orders (
          platform_order_id, customer_id, order_amount, order_status, order_date,
          platform_source, invoice_status, invoice_date, responsible_salesman,
          invoice_number, collection_status, collection_count, last_collection_date,
          last_collection_result, next_followup_date, created_at, updated_at
        ) VALUES ?
      `;
      
      const orderValues = orders.map(order => [
        order.platform_order_id, order.customer_id, order.order_amount, order.order_status, order.order_date,
        order.platform_source, order.invoice_status, order.invoice_date, order.responsible_salesman,
        order.invoice_number, order.collection_status, order.collection_count, order.last_collection_date,
        order.last_collection_result, order.next_followup_date, order.created_at, order.updated_at
      ]);
      
      await sequelize.query(orderQuery, {
        replacements: [orderValues],
        type: Sequelize.QueryTypes.INSERT
      });
      
      console.log(`成功插入 ${orders.length} 条销售订单数据`);
    }
    
    // 验证最终数据
    const [finalCustomerCount] = await sequelize.query('SELECT COUNT(*) as count FROM customers');
    const [finalOrderCount] = await sequelize.query('SELECT COUNT(*) as count FROM sales_orders');
    console.log(`最终客户表记录数: ${finalCustomerCount[0].count}`);
    console.log(`最终销售订单表记录数: ${finalOrderCount[0].count}`);
    
    // 关闭连接
    await sequelize.close();
  } catch (error) {
    console.error('数据填充时出错:', error.message);
  }
}

seedData();